<template>
  <div class="app-header">
    <div class="van-nav-bar van-hairline--bottom">
      <div class="van-nav-bar__content">
        <NavBar left-text="返回" left-arrow @click-left="onClickLeft" />
        <div class="van-nav-bar__title van-ellipsis">购物车</div>
      </div></div></div>
  <div class="cart-page">
    <el-row class="cart-header" type="flex" justify="space-between">
      <el-col :span="12">
      </el-col>
      <el-col :span="12" class="text-right">
      </el-col>
    </el-row>

    <el-row gutter="20">
      <!-- 遍历购物车商品，使用卡片布局展示 -->
      <el-col :span="24" v-for="(item, index) in cartItems" :key="item.id">
        <el-card :body-style="{ padding: '10px' }" class="cart-item-card">
          <div class="cart-item">
            <el-row>
              <el-col :span="6">
                <el-avatar :src="item.img" size="small" />
              </el-col>
              <el-col :span="12">
                <div class="cart-item-info">
                  <h3>{{ item.name }}</h3>
                  <p>单价：￥{{ item.price }}</p>
                  <p>数量：
                    <el-input-number
                        v-model="item.num"
                        :min="1"
                        :max="10"
                        @change="updateTotal"
                        size="small"
                    />
                  </p>
                  <p>总价：￥{{ item.price * item.num }}</p>
                </div>
              </el-col>
              <el-col :span="6" class="text-right">
                <el-button @click="removeItem(item.id)" type="danger" size="small">删除</el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row class="cart-footer" type="flex" justify="end">
      <el-col :span="6">
        <h3>总价：￥{{ totalPrice }}</h3>
      </el-col>
      <el-col :span="6" class="text-right">
        <el-button type="primary" size="large" @click="clearCart">结算</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {ElButton, ElRow, ElCol, ElAvatar, ElCard, ElInputNumber, ElNotification} from 'element-plus'
import {NavBar} from "vant";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
const route = useRoute();
const router = useRouter();
const token = ref('983613da64364eaf9851bb2e1c6db397');
// 定义购物车商品数据
const cartItems = ref([
    {image:'https://www.helloimg.com/i/2025/02/08/67a70261845bf.jpg'}
])
function onClickLeft() {
  router.go(-1);
}
function show(){
  axios.get('http://localhost:8501/cart/list', {
    headers: {
      token: token.value
    }
  }).then(res => {
    console.log(res.data.data)
    cartItems.value = res.data.data
    updateTotal()
  }).catch(error => {
    console.error(error)
  })
}
show()

// 计算总价格
const totalPrice = ref(0)

const updateTotal = () => {
  totalPrice.value = cartItems.value.reduce((total, item) => {
    return total + (item.price * (item.num || 1)); // 防止 num 为 undefined 时出现 NaN
  }, 0);
}

// 删除商品
function removeItem(id) {
  axios.delete('http://localhost:8501/cart/del', {
    headers: {
      token: token.value
    },
    params: {
      id: id // 将id作为查询参数传递
    }
  }).then(response => {
    // 处理删除后的逻辑，例如刷新购物车列表等
    console.log('Item deleted:', response.data);
    show()
  }).catch(error => {
    console.error('Error deleting item:', error);
  });
}



// 清空购物车
const clearCart = () => {
  axios.delete('http://localhost:8501/cart/clear', {
    headers: {
      token: token.value
    }
  }).then(response => {
    show()
  });
  ElNotification({
    message: ('i', { style: 'color: teal' }, '先用后付下单成功'),
  })
}


// 初始化总价
updateTotal()
</script>

<style scoped>
.cart-page {
  margin: 20px;
}

.cart-header h2 {
  margin: 0;
  font-size: 24px;
}

.cart-footer {
  margin-top: 20px;
  font-size: 18px;
}

.text-right {
  text-align: right;
}

.el-button {
  margin-top: 10px;
}

.cart-item-card {
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.cart-item {
  display: flex;
  align-items: center;
}

.cart-item-info h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.cart-item-info p {
  margin: 5px 0;
}
</style>
